<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>企业微信管理后台</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../css/reset.css">
    <link rel="stylesheet" href="../../js/layui/css/layui.css">
    <link rel="stylesheet" href="../../js/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../js/bootstrap/js/bootstrap-table-master/bootstrap-table.min.css">
    <link rel="stylesheet" href="../../css/fonts.css">
    <link rel="stylesheet" href="../../css/main.css">
</head>

<body>
    <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
    <div class="user_manager_page" id="login_data">
        <div class="left_wrapper">
            <!-- 2020-03-02 start -->
            <div class="normal_btn add_group_btn">添加分组</div>
            <!-- <div class="title">
                <span class="text">组别</span>
            </div> -->
            <div class="group_wrapper"></div>
            <!-- 2020-03-02 end -->
        </div>
        <div class="right_wrapper">
            <div class="title selected_dep_value">一组（3人）</div>
            <div class="organizational_section">
                <div class="organizational_wrapper">
                    <div class="normal_btn group_add_member_btn">设置组内成员</div>
                </div>
            </div>
            <div class="table-wrapper">
                <table class="layui-table" id="group_table">
                    <thead>
                        <tr>
                            <th>头像</th>
                            <th>姓名</th>
                            <th>职位</th>
                            <th>性别</th>
                            <th>电话</th>
                            <th class="depart">部门</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div id="paging" style="margin-right: 20px;"></div>
        </div>
    </div>

    <!-- 2020-03-02 start -->
    <!-- 添加分组 -->
    <div class="modal fade normal_modal" id="add_group_modal" tabindex="-1" role="dialog"
        aria-labelledby="add_group_modal_label">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form class="layui-form">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="add_group_modal_label">添加分组</h4>
                    </div>
                    <div class="modal-body">
                        <div class="layui-form-item">
                            <label class="layui-form-label">组名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="group_name" required lay-verify="required" placeholder="请输入名称"
                                    autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" lay-submit
                            lay-filter="add_group_submit">确定</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- 添加分组 -->

    <!-- 修改分组 -->
    <div class="modal fade normal_modal" id="edit_group_modal" tabindex="-1" role="dialog"
        aria-labelledby="edit_group_modal_label">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form class="layui-form">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="edit_group_modal_label">修改分组</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" class="edit_group_id" value="">
                        <div class="layui-form-item">
                            <label class="layui-form-label">组名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="edit_group_name" required lay-verify="required"
                                    placeholder="请输入名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" lay-submit
                            lay-filter="edit_group_submit">确定</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- 修改分组 -->
    <!-- 2020-03-02 end -->

    <!-- 新增成员 模态框 -->
    <div class="modal fade normal_modal" id="add_user_organizational_modal" tabindex="-1" role="dialog"
        aria-labelledby="add_user_organizational_modal_label">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="add_user_organizational_modal_label">选择组内成员</h4>
                </div>
                <div class="modal-body">
                    <div class="select_person_wrapper">
                        <div class="left_wrapper">
                            <div class="add_user_protree_container"></div>
                        </div>
                        <div class="right_wrapper">
                            <div class="title">组内成员</div>
                            <div class="selected">
                                <div class="department_members selected_department" id="add_user_selected_department">

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="add_user_submit_dep_member">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 新增用户组织架构模态框 -->

    <!-- 修改用户组织架构模态框 -->
    <div class="modal fade normal_modal" id="edit_user_organizational_modal" tabindex="-1" role="dialog"
        aria-labelledby="edit_user_organizational_modal_label">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="edit_user_organizational_modal_label">组织架构</h4>
                </div>
                <div class="modal-body">
                    <div class="select_person_wrapper">
                        <div class="left_wrapper">
                            <div class="edit_user_protree_container"></div>
                        </div>
                        <div class="right_wrapper">
                            <div class="title">组织架构</div>
                            <div class="selected">
                                <div class="department_members selected_department" id="edit_user_selected_department">

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="edit_user_submit_dep_member">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 修改用户组织架构模态框 -->
    <!-- 2020-02-14 11:38 end -->

    <script src="../../js/jquery-3.3.1.min.js"></script>
    <script src="../../js/layui/layui.js"></script>
    <script src="../../js/bootstrap/js/bootstrap.min.js"></script>
    <script src="../../js/bootstrap/js/bootstrap-table-master/bootstrap-table.min.js"></script>
    <!-- 树形结构 -->
    <script src="../../js/proTree.js"></script>
    <script>
        var Domain = "http://apichat.vaubang.cn"
        var Authorization = "4B66EFB1B114CF34DACD32F2A81643CC9D136988C2BF433E203FF2501536F882058889F4F2ABDA4DB7F66EA318E412FC79A1C6A4CDF1139EDD1B75D7A182B4EE4557A432941FECE0F797CF5FDB95D24307B83B708214533FE31E9F6AA990FDE2FEA94AD8F624D8E332E5B7978AB6542725943B428EFDB838C346F57809F94CE0143D9E5358BC5BC98588BBC4407EAA125AC070F4061F1D733683B14A006BABB74419513B1B10D2893E9A7D216CD64911276B8BD57C9C482C4081886AA5FBCFCCFC28A4659B78EBFBACC3915D72AB7327"
        // 实例化表单
        layui.use('form', function () {
            var form = layui.form;
            layui.use('layer', function () {
                var layer = layui.layer

                // 默认为第一个组
                var group_id = "" // 默认为第一个组的id
                var group_name = "" // 默认组的名称
                var memberSelected = []; // 组内成员，新建组默认为空
                var groupActived = 0; //默认选中第一个
                var loadModal; // 加载框
                var pagingJson = { // 分页数据 
                    "TagId": 0,
                    "Page": {
                        "Page_id": 1,
                        "Page_size": 5
                    },
                }
                // 获取分组数据
                function getData() {
                    return new Promise((resolve, reject) => {
                        $.ajax({
                            type: "get",
                            url: Domain + "/FindTagList",
                            beforeSend: function (request) {
                                request.setRequestHeader("Authorization", Authorization);
                            },
                            //请求成功
                            success: function (res) {
                                let data = res.Response.Data
                                if (data.length > 0) {
                                    group_id = data[0].TagId;
                                    group_name = data[0].TagName || "";
                                    let html = "";
                                    for (let i = 0; i < data.length; i++) {
                                        let state = ""
                                        if (i == groupActived) {
                                            state = 'active'
                                        }
                                        html += '<div class="group_item ' + state + '" data-id="' + data[i].TagId + '">' +
                                            '<div class="left_box">' +
                                            '<i class="iconfont icon-tuandui"></i>' +
                                            '<span>' + data[i].TagName + '</span>' +
                                            '</div>' +
                                            '<div class="right_box">' +
                                            '<i class="iconfont icon-bianji edit" data-id="' + data[i].TagId + '" data-name="' + data[i].TagName + '"></i>' +
                                            '<i class="iconfont icon-shanchu delete" data-id="' + data[i].TagId + '" data-name="' + data[i].TagName + '"></i>' +
                                            '</div>' +
                                            '</div>';
                                    }
                                    $(".group_wrapper").html(html);
                                }
                                resolve(res.Response.Data);
                            },
                            fail: function (err) {
                                reject(err) // 返回错误信息
                            }
                        })
                    })
                }
                // 获取组成员
                function getGroupMember(group_id) {
                    return new Promise((resolve, reject) => {
                        layer.load()
                        // 请求data
                        pagingJson.TagId = group_id
                        memberSelected = []
                        $.ajax({
                            type: "post",
                            url: Domain + "/FindTagMemberList",
                            beforeSend: function (request) {
                                request.setRequestHeader("Authorization", Authorization);
                            },
                            data: pagingJson,
                            //请求成功
                            success: function (res) {
                                let data = res.Response.Data
                                let html = ""
                                if (data.ResultList.length > 0) {
                                    for (var i = 0; i < data.ResultList.length; i++) {
                                        html += '<tr><td class="avatar">' +
                                            '<img src="' + data.ResultList[i].Avatar + '">' +
                                            '</td>' +
                                            '<td class="user_name">' + data.ResultList[i].Name + '</td>' +
                                            '<td class="user_role">' + data.ResultList[i].Position + '</td>' +
                                            '<td class="user_sex">' + data.ResultList[i].Sex + '</td>' +
                                            '<td class="user_phone">' + data.ResultList[i].Mobile + '</td>' +
                                            '<td class="user_organization">' + data.ResultList[i].DepartmentName +
                                            '</td></tr>';
                                        let member = {
                                            id: data.ResultList[i].UserId,
                                            name: data.ResultList[i].Name,
                                            pid: data.ResultList[i].ParentId,
                                            department: false,
                                            Useful: true
                                        }
                                        memberSelected.push(member);
                                    }
                                    $("#group_table tbody").html(html)
                                } else {
                                    $("#group_table tbody").html("")
                                }
                                // 表格分页
                                layui.use('laypage', function () {
                                    var laypage = layui.laypage;
                                    //执行一个laypage实例
                                    laypage.render({
                                        elem: 'paging',
                                        limit: 5,
                                        theme: '#E51C23',
                                        count: data.TotalRecords, //数据总数，从服务端得到
                                        jump: function (obj, first) {
                                            pagingJson.Page.Page_id = obj.curr
                                            pagingJson.Page.Page_size = obj.limit
                                            //首次不执行
                                            if (!first) {
                                                getGroupMember(pagingJson.TagId)
                                            }
                                        }
                                    });
                                })
                                resolve(data)
                            },
                            fail: function (err) {
                                reject(err) // 返回错误信息
                            }
                        })
                    })
                }

                // 获取组织架构
                function getDepart() {
                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: Domain + "/FindDepartmentAndMember",
                            type: "get",
                            beforeSend: function (request) {
                                request.setRequestHeader("Authorization", Authorization);
                            },
                            success: function (res) {
                                let proArr = []
                                if (res && res.Response.Code == 200) {
                                    let data = res.Response.Data;
                                    for (var i = 0; i < data.length; i++) {
                                        let datainfo = {
                                            id: data[i].Id,
                                            name: data[i].Name,
                                            pid: data[i].PId,
                                            department: data[i].Department,
                                            Useful: data[i].Useful
                                        };
                                        proArr.push(datainfo);
                                    }
                                }
                                else {
                                    FindLoginState(res.Response.Msg + ":CreateMember")
                                }
                                resolve(proArr)
                            },
                            error: function (err) {
                                reject(err)
                            }
                        })
                    })
                }
                // 同时获取分组和组内成员
                function get_group_member(groupActived) {
                    let index = groupActived || 0
                    getData().then((data) => {
                        console.log('组列表', data);
                        group_id = data[index].TagId;
                        group_name = data[index].TagName || "";
                        // 获取组成员
                        getGroupMember(data[index].TagId).then((data) => {
                            console.log('组成员', data)
                            $(".selected_dep_value").text(group_name + '（' + data.ResultList.length + '人）')
                            $(".group_wrapper .group_item").eq(index).addClass('active').siblings().removeClass('active')
                            layer.closeAll('loading') // 关闭加载框
                        })
                    })
                    
                }
                get_group_member() // 初始化运行获得组和组成员

                // 切换组别
                $(".group_wrapper").on('click', '.group_item', function () {
                    $(this).addClass('active').siblings().removeClass('active')
                    group_id = $(this).attr('data-id') // 组id
                    pagingJson.TagId = group_id
                    // 2020-03-02 start
                    let group_name = $(this).find('.left_box span').text() // 组名
                    // 2020-03-02 end
                    console.log(group_id, group_name)
                    memberSelected = []
                    // 切换组别后需要请求ajax获得该组别内的组成员信息 赋值给memberSelected
                    // 将表格与赋值给memberSelected值刷新
                    // 获取组成员
                    getGroupMember(group_id).then((data) => {
                        console.log('组成员', data)
                        $(".selected_dep_value").text(group_name + '（' + data.ResultList.length + '人）')
                        layer.closeAll('loading') // 关闭加载框
                    })
                })

                // 设置组内成员
                $(".group_add_member_btn").click(function () {
                    console.log('memberSelected', memberSelected)
                    if (memberSelected.length > 0) {
                        let html = ""
                        for (let i = 0; i < memberSelected.length; i++) {
                            html += `
                        <div class="dep_item">
                            <i class="iconfont icon-wenjianjia"></i>
                            <span data-id="${memberSelected[i].id}" data-pid="${memberSelected[i].pid}" data-dep="${memberSelected[i].department}" data-useful="${memberSelected[i].Useful}">${memberSelected[i].name}</span>
                            <i class="iconfont icon-shanchu delete_dep_mem"></i>
                        </div>
                        `
                        }
                        $("#add_user_selected_department").html(html)
                    } else {
                        $("#add_user_selected_department").html("")
                    }
                    $("#add_user_organizational_modal").modal('show')
                })

                getDepart().then((arr) => {
                    console.log('树形data', arr)
                    //标题的图标是集成bootstrap 的图标  更改 请参考bootstrap的字体图标替换自己想要的图标
                    $(".add_user_protree_container").ProTree({
                        arr: arr,
                        close: true,
                        simIcon: "iconfont icon-wenjianjia", //单个标题字体图标 不传默认glyphicon-file
                        mouIconOpen: "iconfont icon-wenjianjia1", //含多个标题的打开字体图标  不传默认glyphicon-folder-open
                        mouIconClose: "iconfont icon-wenjianjia", //含多个标题的关闭的字体图标  不传默认glyphicon-folder-close
                        callback: function (id, name, pid, department, useful) {
                            let data = {
                                id: id,
                                name,
                                pid: parseInt(pid),
                                department,
                                Useful: useful
                            };
                            if (department == true || department == 'true') {
                                data.id = parseInt(id)
                                data.department = true
                            } else if (department == 'false') {
                                data.department = false
                            }
                            if (useful == 'true') {
                                data.Useful = true
                            } else {
                                data.Useful = false
                            }
                            if (!data.department && data.Useful) {
                                if (memberSelected.length > 0) {
                                    for (let i = 0; i < memberSelected.length; i++) {
                                        if (memberSelected[i].id == data.id) {
                                            layer.msg('组内已有该成员')
                                            return false
                                        }
                                    }
                                }
                                memberSelected.push(data)
                                $("#add_user_selected_department").append(`
                        <div class="dep_item">
                            <i class="iconfont icon-wenjianjia"></i>
                            <span data-id="${data.id}" data-pid="${data.pid}" data-dep="${data.department}" data-useful="${data.Useful}">${data.name}</span>
                            <i class="iconfont icon-shanchu delete_dep_mem"></i>
                        </div>
                        `);
                            }
                        }
                    });
                })

                // 删除成员
                $(".department_members").on("click", ".delete_dep_mem", function () {
                    let id = $(this)
                        .siblings("span")
                        .attr("data-id");
                    let dep = $(this)
                        .siblings("span")
                        .attr("data-dep");
                    $(this)
                        .parent()
                        .remove();
                    for (let i = 0; i < memberSelected.length; i++) {
                        if (id == memberSelected[i].id) {
                            memberSelected.splice(i, 1);
                            break;
                        }
                    }
                });

                // 设置组成员 确认
                $("#add_user_submit_dep_member").click(function () {
                    console.log('memberSelected', memberSelected, '组id', group_id) // 拿到已选择的人员
                    // 组id为 group_id
                    let postdata = {
                        "TagId": group_id,
                        "Userlist": []
                    }
                    for (let i = 0; i < memberSelected.length; i++) {
                        postdata.Userlist.push(memberSelected[i].id)
                    }
                    console.log('memberSelected', memberSelected, '组id', group_id, postdata) // 拿到已选择的人员
                    // 请求ajax
                    $.ajax({
                        url: Domain + "/ModifyTagMember",
                        type: "post",
                        data: postdata,
                        beforeSend: function (request) {
                            request.setRequestHeader("Authorization", Authorization);
                        },
                        success: function (res) {
                            if (res) {
                                if (res.Response.Code == 200) {
                                    // 执行完毕后
                                    memberSelected = [];
                                    getGroupMember(group_id).then((data) => {
                                        console.log('组成员', data)
                                        $(".selected_dep_value").text(group_name + '（' + data.ResultList.length + '人）')
                                        layer.closeAll('loading') // 关闭加载框
                                    })
                                    $("#add_user_organizational_modal").modal('hide')
                                    layer.msg('设置成功')
                                }
                                else {
                                    FindLoginState(res.Response.Msg + ":ModifyTagMember")
                                }
                            }
                        },
                        error: function (err) {
                            console.log(err)
                        }
                    })
                });

                // 2020-03-02 start
                // 打开添加分组modal
                $('.add_group_btn').click(function () {
                    $("#add_group_modal").modal('show')
                })

                // 添加分组 确定提交
                form.on('submit(add_group_submit)', function (data) {
                    let name = data.field.group_name // 组名称
                    // 拿到组名称请求ajax
                    $.ajax({
                        url: Domain + "/AddTag?tagName=" + name,
                        type: "get",
                        beforeSend: function (request) {
                            request.setRequestHeader("Authorization", Authorization);
                        },
                        success: function (res) {
                            if (res && res.Response.Code == 200) {
                                get_group_member();
                                $("#add_group_modal").modal('hide')
                                layer.msg('添加成功')
                            }
                            else {
                                FindLoginState(res.Response.Msg + ":CreateMember")
                            }
                        },
                        error: function (err) {
                            console.log(err)
                        }
                    })
                })

                // 点击 修改组
                $(".group_wrapper").on('click', '.group_item .right_box .edit', function (e) {
                    e.stopPropagation()
                    let group_id = $(this).attr('data-id') // 拿到当前组的id
                    let group_name = $(this).attr('data-name') // 拿到当前组的名称
                    console.log(group_id, group_name)
                    $("#edit_group_modal").modal('show')
                    $(".edit_group_id").val(group_id) // 将组id赋值给隐藏域
                    $("input[name=edit_group_name]").val(group_name) // 将组名称赋值给修改组名称框
                })

                // 修改分组 确定提交
                form.on('submit(edit_group_submit)', function (data) {
                    let name = data.field.edit_group_name // 组名称
                    let group_id = $(".edit_group_id").val() // 组id
                    let postdata = {
                        "TagId": group_id,
                        "TagName": name
                    }
                    
                    $(".group_wrapper .group_item").each(function(i){
                        if ($(this).hasClass('active')) {
                            groupActived = i
                        }
                    })

                    // 拿到组名称请求ajax
                    $.ajax({
                        url: Domain + "/ModifyTagName",
                        type: "post",
                        data: postdata,
                        beforeSend: function (request) {
                            request.setRequestHeader("Authorization", Authorization);
                        },
                        success: function (res) {
                            if (res) {
                                if (res.Response.Code == 200) {
                                    // 执行完毕后
                                    get_group_member(groupActived)
                                    $("#edit_group_modal").modal('hide')
                                    layer.msg('修改成功')
                                }
                                else {
                                    FindLoginState(res.Response.Msg + ":ModifyTagName")
                                }
                            }
                        },
                        error: function (err) {
                            console.log(err)
                        }
                    })
                })

                // 删除分组
                $(".group_wrapper").on('click', '.group_item .right_box .delete', function (e) {
                    e.stopPropagation()
                    let group_id = $(this).attr('data-id') // 拿到当前组的id
                    let group_name = $(this).attr('data-name') // 拿到当前组的名称
                    console.log(group_id, group_name)
                    layer.confirm('确定删除 ' + group_name + ' 吗？', {
                        btn: ['取消', '确认'] //按钮
                    }, function (index) {
                        layer.close(index)
                    }, function () {
                        $.ajax({
                            url: Domain + "/RemoveTag?Id=" + group_id,
                            type: "get",
                            beforeSend: function (request) {
                                request.setRequestHeader("Authorization", Authorization);
                            },
                            success: function (res) {
                                if (res && res.Response.Code == 200) {
                                    // 执行完毕后
                                    get_group_member()
                                    layer.msg('删除成功')
                                }
                                else {
                                    FindLoginState(res.Response.Msg + ":RemoveTag")
                                }
                            },
                            error: function (err) {
                                console.log(err)
                            }
                        })
                    })
                })
                // 2020-03-02 end

                // $("#export_btn").click(function () {
                //     let paramsJson = {
                //         "Page": {
                //             "Page_id": 1,
                //             "Page_size": 5
                //         },
                //         "StartTime": "",
                //         "EndTime": "",
                //         "UserId": []
                //     }
                //     let xhr = new XMLHttpRequest()
                //     xhr.responseType = "blob"
                //     xhr.open("POST", Domain + "/EXPORTGroupChatStatistic", true)
                //     xhr.setRequestHeader("Content-type", "application/json")
                //     xhr.setRequestHeader("Authorization", Authorization)
                //     xhr.onload = function () {
                //         const blob = this.response
                //         const objectUrl = URL.createObjectURL(blob)
                //         const a = document.createElement("a")
                //         document.body.appendChild(a)
                //         a.style = "display: none"
                //         a.href = objectUrl
                //         a.download = 'excel.xlsx'
                //         a.click()
                //         document.body.removeChild(a)
                //         return
                //     }
                //     xhr.send(JSON.stringify(paramsJson))
                // })
            })
        })
    </script>
</body>

</html>